﻿#ifndef CWORKTEST_HTTPCLIENT_H
#define CWORKTEST_HTTPCLIENT_H
#pragma once
#include <string>
#include <map>
#include <vector>
#include <memory>
#include <curl/curl.h>

struct HttpResponse {
    long status_code = 0;               // HTTP 状态码，如 200
    std::string body;                   // 响应体
    std::map<std::string, std::string> headers; // 响应头，键小写化
    std::string error;                  // 如果请求失败，返回 libcurl 的错误描述
};

class HttpClient {
public:
    // 获取单例
    static HttpClient& getInstance();

    // 基本接口：
    // GET 请求
    HttpResponse get(const std::string& url,
                     const std::map<std::string, std::string>& request_headers = {},
                     long timeout_seconds = 30);

    // POST 请求（支持任意 body，常用于 JSON）
    HttpResponse post(const std::string& url,
                      const std::string& body,
                      const std::map<std::string, std::string>& request_headers = {},
                      long timeout_seconds = 30);

    // 便捷：POST JSON
    HttpResponse postJson(const std::string& url,
                          const std::string& json,
                          const std::map<std::string, std::string>& extra_headers = {},
                          long timeout_seconds = 30);

    // 禁止复制/移动
    HttpClient(const HttpClient&) = delete;
    HttpClient& operator=(const HttpClient&) = delete;
    HttpClient(HttpClient&&) = delete;
    HttpClient& operator=(HttpClient&&) = delete;

private:
    HttpClient();
    ~HttpClient();

    // 内部通用请求函数
    HttpResponse performRequest(const std::string& method,
                                const std::string& url,
                                const std::string* body,
                                const std::map<std::string, std::string>& request_headers,
                                long timeout_seconds);

    // 工具：把 map 转成 curl_slist（由 CurlHeaders RAII 管理）
    struct CurlSlist {
        struct curl_slist* list = nullptr;
        ~CurlSlist() {
            if (list) curl_slist_free_all(list);
        }
        void append(const std::string& line) {
            list = curl_slist_append(list, line.c_str());
        }
    };
};
#endif //CWORKTEST_HTTPCLIENT_H
